package com.xz.diagnosis.service.impl;

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xz.common.core.domain.model.LoginUser;
import com.xz.common.exception.ServiceException;
import com.xz.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.utils.RedisCode;
import com.xz.common.utils.SecurityUtils;
import com.xz.diagnosis.dto.DiagnosisPackageDto;
import com.xz.diagnosis.service.IDiagnosisPackageItemService;
import com.xz.diagnosis.vo.DiagnosisPackageVo;
import com.xz.diagnosis.vo.PackageUnionItemVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xz.diagnosis.mapper.DiagnosisPackageMapper;
import com.xz.diagnosis.domain.DiagnosisPackage;
import com.xz.diagnosis.service.IDiagnosisPackageService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 诊疗套餐Service业务层处理
 *
 * @author xz
 * @date 2024-03-14
 */
@Service
public class DiagnosisPackageServiceImpl extends ServiceImpl<DiagnosisPackageMapper, DiagnosisPackage> implements IDiagnosisPackageService {
  @Autowired
  private DiagnosisPackageMapper diagnosisPackageMapper;
  @Autowired
  private IDiagnosisPackageItemService diagnosisPackageItemService;

  /**
   * 查询诊疗套餐
   *
   * @param id 诊疗套餐主键
   * @return 诊疗套餐
   */
  @Override
  public DiagnosisPackage selectDiagnosisPackageById(Long id) {
    return diagnosisPackageMapper.selectDiagnosisPackageById(id);
  }

  /**
   * 查询诊疗套餐列表
   *
   * @param diagnosisPackage 诊疗套餐
   * @return 诊疗套餐
   */
  @Override
  public List<DiagnosisPackage> selectDiagnosisPackageList(DiagnosisPackage diagnosisPackage) {
    return diagnosisPackageMapper.selectDiagnosisPackageList(diagnosisPackage);
  }

  /**
   * 查询诊疗套餐列表
   *
   * @param diagnosisPackage 诊疗套餐
   * @return 诊疗套餐
   */
  @Override
  public List<DiagnosisPackageVo> selectDiagnosisPackageVoList(DiagnosisPackage diagnosisPackage) {
    return diagnosisPackageMapper.selectDiagnosisPackageVoList(diagnosisPackage);
  }

  /**
   * 查询诊疗套餐与项目合并列表
   *
   * @param diagnosisPackage 诊疗套餐
   * @return
   */
  @Override
  public List<PackageUnionItemVo> selectPackageUnionItemList(DiagnosisPackage diagnosisPackage) {
    return diagnosisPackageMapper.selectPackageUnionItemList(diagnosisPackage);
  }

  /**
   * 新增诊疗套餐
   *
   * @param dto 诊疗套餐
   * @return 结果
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public int insertDiagnosisPackage(DiagnosisPackageDto dto) {

    DiagnosisPackage entity = new DiagnosisPackage();
    BeanUtils.copyProperties(dto, entity);
    //编号
    entity.setPackageNo(RedisCode.getCode("ZLTK"));
    //校验字段
    verifyFields(entity);
    //填充创建人信息
    LoginUser user = SecurityUtils.getLoginUser();
    entity.setCreateBy(user.getUserId());
    entity.setCreateTime(DateUtils.getNowDate());
    entity.setTenantId(user.getTenantId());
    entity.setDeptId(user.getDeptId());
    int res = diagnosisPackageMapper.insertDiagnosisPackage(entity);
    if (0 < res) {
      //添加项目
      diagnosisPackageItemService.insertForPackage(entity, dto.getItems(), false);
    }
    return res;
  }

  /**
   * 修改诊疗套餐
   *
   * @param dto 诊疗套餐
   * @return 结果
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public int updateDiagnosisPackage(DiagnosisPackageDto dto) {

    DiagnosisPackage entity = baseMapper.selectById(dto.getId());
    if (null != entity) {
      BeanUtils.copyProperties(dto, entity);
      //校验字段
      verifyFields(entity);
      //填充更新人信息
      LoginUser user = SecurityUtils.getLoginUser();
      entity.setUpdateBy(user.getUserId());
      entity.setUpdateTime(DateUtils.getNowDate());
      int res = diagnosisPackageMapper.updateDiagnosisPackage(entity);
      if (0 < res) {
        //添加项目
        diagnosisPackageItemService.insertForPackage(entity, dto.getItems(), true);
      }
      return res;
    }
    return 0;
  }


  private void verifyFields(DiagnosisPackage entity) {

    // 校验名称唯一性
    LambdaQueryWrapper<DiagnosisPackage> wrapper = Wrappers.lambdaQuery(DiagnosisPackage.class);
    wrapper.eq(DiagnosisPackage::getPackageName, entity.getPackageName());
    wrapper.ne(null != entity.getId(), DiagnosisPackage::getId, entity.getId());
    wrapper.eq(DiagnosisPackage::getDelFlag, 0);
    int count = diagnosisPackageMapper.selectCount(wrapper);
    if (0 < count) {
      throw new ServiceException("该套餐名称已存在");
    }
  }


  /**
   * 批量删除诊疗套餐
   *
   * @param ids 需要删除的诊疗套餐主键
   * @return 结果
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public int deleteDiagnosisPackageByIds(Long[] ids) {

    List<DiagnosisPackage> packages = diagnosisPackageMapper.selectBatchIds(Arrays.asList(ids));
    if (CollectionUtils.isEmpty(packages)) {
      // 获取不到数据，有可能是已经删除了，直接返回成功给前台即可
      return 1;
    }
    // 校验套数是否启用中。
    packages.forEach(data -> {
      if ("1".equals(data.getStatus())) {
        throw new ServiceException("套餐" + data.getPackageName() + "正在启用中，无法删除。");
      }
    });
    // 开始删除套餐
    int res = diagnosisPackageMapper.deleteDiagnosisPackageByIds(ids);
    if(0 < res){
      // 开始删除套餐下的项目
      diagnosisPackageItemService.deleteByPackageIds(ids);
    }
    return res;
  }

}
